package com.apps.ftapp.util;

import android.os.CountDownTimer;
import android.view.View;
import android.widget.TextView;

/**
 * Created by lyli on 2017/10/13.
 */

public class Timer {


    private TextView textView;
    private MyCountDownTimer timer;
    private final long TIME = 2 * 60 * 60 * 1000L;
    private final long INTERVAL = 1000L;


    public Timer(TextView textView) {

        this.textView = textView;
    }

    public class MyCountDownTimer extends CountDownTimer {
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            long time = millisUntilFinished / 1000;

            if (time <= 59) {
                textView.setText(String.format(" 00:%02d", time));
            } else {
                textView.setText(String.format(" %02d:%02d", time / 60, time % 60));
            }
        }

        @Override
        public void onFinish() {
            textView.setText("00:00");
            cancelTimer();
        }
    }

    public void start(View view) {
        startTimer();
    }

    public void cancel(View view) {
        textView.setText("00:00");
        cancelTimer();
    }

    /**
     * 开始倒计时
     */
    private void startTimer() {
        if (timer == null) {
            timer = new MyCountDownTimer(TIME, INTERVAL);
        }
        timer.start();
    }

    /**
     * 取消倒计时
     */
    private void cancelTimer() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }


}
